/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.template.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.algorithmConfig.entity.AlgorithmConfig;
import vip.xiaonuo.biz.modular.algorithmConfig.entity.DictAlgo;
import vip.xiaonuo.biz.modular.algorithmConfig.mapper.AlgorithmConfigMapper;
import vip.xiaonuo.biz.modular.algorithmConfig.param.AlgorithmConfigAddParam;
import vip.xiaonuo.biz.modular.template.param.*;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.template.entity.Template;
import vip.xiaonuo.biz.modular.template.mapper.TemplateMapper;
import vip.xiaonuo.biz.modular.template.service.TemplateService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 算法配置Service接口实现类
 *
 * @author mengxiaowei
 * @date  2024/09/23 18:12
 **/
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template> implements TemplateService {

    @Resource
    private AlgorithmConfigMapper algorithmConfigMapper;

    @Resource
    private TemplateMapper templateMapper;


    @Resource
    private RedisTemplate<String, Object> redisTemplate;



    @Override
    public Page<Template> page(TemplatePageParam templatePageParam) {
        QueryWrapper<Template> queryWrapper = new QueryWrapper<Template>().checkSqlInjection();
        if(ObjectUtil.isAllNotEmpty(templatePageParam.getSortField(), templatePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(templatePageParam.getSortOrder());
            queryWrapper.orderBy(true, templatePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(templatePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(Template::getSortCode);
        }

        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }


    @Override
    public Page<TemplateSelectParam> pageAlgorithm(TemplatePageParam templatePageParam) {
        Page<Template> templatePage = page(templatePageParam);
        List<Template> templateList = templatePage.getRecords();
        Page<TemplateSelectParam> page = new Page<TemplateSelectParam>();
        List<TemplateSelectParam> templateSelectParamList = new ArrayList<TemplateSelectParam>();
        List<DictAlgo> dictMap = algorithmConfigMapper.selectDictMap();
        /*HashMap map = new HashMap();
        for (int i = 0; i < dictMap.size(); i++) {
            map.put(dictMap.get(i).getDictValue(), dictMap.get(i).getDictLabel());
        }*/

        for (int i = 0; i < templateList.size(); i++) {
            TemplateSelectParam templateSelectParam = new TemplateSelectParam();
            List<String> stringList = algorithmConfigMapper.selectListAlgorithmConfig(templateList.get(i).getId());
             String name = "";

             for (int j = 0; j < stringList.size(); j++) {

                //Object obj = map.get(stringList.get(j));
                name = name+stringList.get(j)+",";
            }

            name = name.substring(0, name.length() - 1);
            templateSelectParam.setId(templateList.get(i).getId());
            templateSelectParam.setTemplateName(templateList.get(i).getTemplateName());
            templateSelectParam.setTemplateType(templateList.get(i).getTemplateType());
            templateSelectParam.setTimeSlot(templateList.get(i).getTimeSlot());
            templateSelectParam.setTriggerMode(templateList.get(i).getTriggerMode());
            templateSelectParam.setAlgorithmConfigNameList(name);
            templateSelectParamList.add(templateSelectParam);
        }

        page.setRecords(templateSelectParamList);
        page.setCurrent(templatePage.getCurrent());
        page.setSize(templatePage.getSize());
        page.setTotal(templatePage.getTotal());
        return page;
    }









    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TemplateAddParam templateAddParam) {
        Template template = BeanUtil.toBean(templateAddParam, Template.class);
        templateMapper.insert(template);

        JSONObject jsonObject = new JSONObject();
        jsonObject.set("triggerMode", template.getTriggerMode());
        jsonObject.set("templateType", template.getTemplateType());
        jsonObject.set("timeSlot", template.getTimeSlot());
        redisTemplate.opsForHash().putAll("template"+"-"+template.getId(), jsonObject);




        for (int i = 0; i < templateAddParam.getAlgorithmConfigParams().size(); i++) {
            List<AlgorithmConfigAddParam> algorithmConfigAddParams = templateAddParam.getAlgorithmConfigParams();
            AlgorithmConfig algorithmConfig = BeanUtil.toBean(algorithmConfigAddParams.get(i), AlgorithmConfig.class);
            algorithmConfig.setTemplateId(template.getId());
            algorithmConfigMapper.insert(algorithmConfig);
        }





    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(TemplateEditParam templateEditParam) {
        Template template = this.queryEntity(templateEditParam.getId());
        BeanUtil.copyProperties(templateEditParam, template);
        this.updateById(template);

        JSONObject jsonObject = new JSONObject();
        jsonObject.set("triggerMode", template.getTriggerMode());
        jsonObject.set("templateType", template.getTemplateType());
        jsonObject.set("timeSlot", template.getTimeSlot());
        redisTemplate.opsForHash().putAll("template"+"-"+template.getId(), jsonObject);




        algorithmConfigMapper.deleteAlgorithmConfig(templateEditParam.getId());
        for (int i = 0; i < templateEditParam.getAlgorithmConfigParams().size(); i++) {
            List<AlgorithmConfigAddParam> algorithmConfigAddParams = templateEditParam.getAlgorithmConfigParams();
            AlgorithmConfig algorithmConfig = BeanUtil.toBean(algorithmConfigAddParams.get(i), AlgorithmConfig.class);
            algorithmConfig.setTemplateId(template.getId());
            algorithmConfigMapper.insert(algorithmConfig);
        }





    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<TemplateIdParam> templateIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(templateIdParamList, TemplateIdParam::getId));
    }

    @Override
    public Template detail(TemplateIdParam templateIdParam) {
        return this.queryEntity(templateIdParam.getId());
    }

    @Override
    public Template queryEntity(String id) {
        Template template = this.getById(id);
        if(ObjectUtil.isEmpty(template)) {
            throw new CommonException("算法配置不存在，id值为：{}", id);
        }
        return template;
    }
}
